package yz.zookeeper;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.List;

public class zookeeperDemo4 {
    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        ZooKeeper zooKeeper = new ZooKeeper("master:2181,node1:2181,node2:2181", 15000, new Watcher() {
            //对于接口对象创建时，要实现抽象函数
            @Override
            public void process(WatchedEvent watchedEvent) {
                System.out.println("连接正在连接。。。连接成功");
            }
        });
//        List<String> children = zooKeeper.getChildren("/api", false);
//        for (String child : children) {
//            System.out.println(child);
//        }


        String path = "/api";
        child(path,zooKeeper);
        zooKeeper.close();
        //这样只能看到/api下的子文件，而不能看到子文件以下的子文件   这时我们就引入了递归
    }
    public static void child(String path,ZooKeeper zooKeeper) throws InterruptedException, KeeperException {
        Stat exists = zooKeeper.exists(path, false);
        if(exists.getNumChildren()>0){
            List<String> children = zooKeeper.getChildren(path, false);
            //这样就可以遍历每一个子节点
            for (String child : children) {
                System.out.println("获取到子节点："+path+"/"+child);
                child(path+"/"+child,zooKeeper);
            }
        }

    }
}
